package com.dayuanit.dy17.atm.controller;

import com.dayuanit.dy17.atm.config.AtmPropertiesConfig;
import com.dayuanit.dy17.atm.dto.ResponseDTO;
import com.dayuanit.dy17.atm.service.IRedisService;
import com.dayuanit.dy17.atm.service.IUserService;
import com.dayuanit.dy17.atm.service.impl.RedisServiceTmpleteImpl;
import com.dayuanit.dy17.atm.util.SignUtils;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpSession;

@RestController
public class EmailController extends BaseController {

    private static final String activeEmailPattern = "请点击连接地址，激活邮箱：%s/email/activeEmail?activeEmail=%s&createTime=%s&sign=%s";
    private static final String resetPwdEmailPattern = "请点击以下地址，进行密码重置：%s/user/toResetPassword?bindEmail=%s&createTime=%s&sign=%s，请在%s秒内重置，否则过期无效。";

    @Autowired
    private IUserService userService;

    @Autowired
    private JavaMailSender javaMailSender;

    @Resource(type = RedisServiceTmpleteImpl.class)
    private IRedisService redisService;

    @RequestMapping(value = "/email/sendEmail", method = RequestMethod.POST)
    public ResponseDTO sendEmail(String toEmail, HttpSession session) {
        MimeMessage message = javaMailSender.createMimeMessage();

        MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(message);
        try {
            mimeMessageHelper.setFrom("dayuanitatm@163.com");
            mimeMessageHelper.setTo(toEmail);
            mimeMessageHelper.setSubject("ATM系统绑定邮箱");

            long createTime = System.currentTimeMillis();
            String sign = signUtils.createActiveEmailSign(toEmail, getUsername(session), createTime);

            String msg = String.format(activeEmailPattern, atmPropertiesConfig.getAtmHost(), toEmail, createTime, sign);

            mimeMessageHelper.setText(msg);
            javaMailSender.send(message);
            return ResponseDTO.success();
        } catch (MessagingException e) {
            e.printStackTrace();
            return ResponseDTO.fail("邮件发送失败");
        }
    }

    @RequestMapping(value = "/email/activeEmail")
    public ResponseDTO activeEmail(String activeEmail, String sign,  long createTime, HttpSession session) {
        System.out.println("------activeEmail()------" + activeEmail + "  sign=" +sign);

        // 将email绑定到用户账号里
        userService.bindEmail(getUserId(session), activeEmail, sign, createTime);
        return ResponseDTO.success();
    }

    @RequestMapping(value = "/email/sendResetPasswordEmail")
    public ResponseDTO sendResetPasswordEmail(String email) {
        if (!redisService.saveResetPwdEmail(email)) {
            return ResponseDTO.fail("手速太快，请稍后再发");
        }

        MimeMessage message = javaMailSender.createMimeMessage();

        MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(message);
        try {
            mimeMessageHelper.setFrom("dayuanitatm@163.com");
            mimeMessageHelper.setTo(email);
            mimeMessageHelper.setSubject("ATM系统重置密码邮件");

            //明文格式=email + 盐值 + 创建时间
            long createTime = System.currentTimeMillis();
            String sign = signUtils.createResetPwdSign(email, createTime);

            String msg = String.format(resetPwdEmailPattern, atmPropertiesConfig.getAtmHost(), email, createTime, sign, atmPropertiesConfig.getResetPwdExpire());

            mimeMessageHelper.setText(msg);
            javaMailSender.send(message);
            return ResponseDTO.success();
        } catch (MessagingException e) {
            e.printStackTrace();
            return ResponseDTO.fail("邮件发送失败");
        }
    }


}
